import { setToken, getToken, removeToken } from '@/utils/auth'
import { login, getUserInfoApi, getUserDetailById } from '@/api/user'
export default {
  namespaced: true,
  state() {
    return {
      // 记得从本地获取token 要不vuex 刷新会从新赋值为空
      token: getToken() || null,
      userInfo: {}
    }
  },
  mutations: {
    // 设置token
    setToken(state, newToken) {
      state.token = newToken
      setToken(newToken)
    },
    // 移除token
    clearToken(state) {
      state.token = null
      removeToken()
    },
    // 设置用户信息
    setUserInfo(state, newUserInfo) {
      state.userInfo = newUserInfo
    },
    // 移除用户信息
    clearUserInfo(state) {
      state.userInfo = {}
    }
  },
  actions: {
    // 登录请求
    async userLogin(store, obj) {
      const res = await login(obj)
      store.commit('setToken', res.data)
    },
    // 获取用户信息的请求
    async getUserInfo(store) {
      const info = await getUserInfoApi()
      console.log(info)
      store.commit('setUserInfo', info.data)
      const headPortrait = await getUserDetailById(info.data.userId)
      console.log(headPortrait)
      store.commit('setUserInfo', { ...info.data, ...headPortrait.data })
    }
  }
}

